package com.tanhua.server.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.dubbo.server.api.QuanZiApi;
import com.tanhua.dubbo.server.api.VideoApi;
import com.tanhua.dubbo.server.pojo.PageInfo;
import com.tanhua.dubbo.server.pojo.Video;
import com.tanhua.server.pojo.User;
import com.tanhua.server.pojo.UserInfo;
import com.tanhua.server.utils.UserThreadLocal;
import com.tanhua.server.vo.PageResult;
import com.tanhua.server.vo.PicUploadResult;
import com.tanhua.server.vo.VideoVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;

/**
 * @description:
 * @author: Administrator
 * @date: Created in 2021/2/22 14:39
 * @version: 0.0.1
 * @modified By:
 */
@Service
public class VideoService {

    @Reference(version = "1.0.0")
    private VideoApi videoApi;

    @Autowired
    private PicUploadService picUploadService;

    @Autowired
    protected FastFileStorageClient storageClient;

    @Autowired
    private FdfsWebServer fdfsWebServer;

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private RedisTemplate<String,String>redisTemplate;

    @Reference(version = "1.0.0")
    private QuanZiApi quanZiApi;
    /**
     * @description 保存小视频
     * @author
     * @date
     * @param
     *@return
     */
    public String saveVideo(MultipartFile picFile, MultipartFile videoFile) {
        User user= UserThreadLocal.get();
        Video video=new Video();
        video.setUserId(user.getId());
        video.setSeeType(1);
        try {
            //上传封面图片
            PicUploadResult picUploadResult = this.picUploadService.upload(picFile);
            video.setPicUrl(picUploadResult.getName()); //图片路径
            //上传视频
            StorePath storePath = this.storageClient.uploadFile(videoFile.getInputStream(), videoFile.getSize(),
                    StringUtils.substringAfter(videoFile.getOriginalFilename(), "."), null);
            video.setVideoUrl(this.fdfsWebServer.getWebServerUrl()+"/"+storePath.getFullPath());
            this.videoApi.saveVideo(video);
            return this.videoApi.saveVideo(video);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }
    /**
     * @description 小视频列表
     * @author
     * @date
     * @param
     *@return
     */
    public PageResult queryVideoList(Integer page, Integer pageSize) {
        User user=UserThreadLocal.get();
        PageResult pageResult=new PageResult();
        pageResult.setCounts(0);
        pageResult.setPages(0);
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);
        PageInfo<Video> pageInfo = null;
        //先从redis进行命中，r如果命中则返回推荐列表，如果未命中查询默认列表
        String redisVideo=this.redisTemplate.opsForValue().get("QUANZI_VIDEO_RECOMMEND_"+user.getId());
                if(StringUtils.isNotEmpty(redisVideo)){
                    String[] vids = StringUtils.split(redisVideo, ",");
                    int startIndex=(page-1)*pageSize;
                    if(startIndex<vids.length){
                        int endIndex=startIndex+pageSize-1;
                        if(endIndex>=vids.length){
                            endIndex=vids.length-1;
                        }
                        List<Long>vidList=new ArrayList<>();
                        for(int i=startIndex;i<=endIndex;i++){
                            vidList.add(Long.valueOf(vids[i]));
                        }
                       List<Video>videoList= this.videoApi.queryVideoListByVids(vidList);
                        pageInfo=new PageInfo<>();
                        pageInfo.setRecords(videoList);
                    }
                }
                if(pageInfo==null){
                    pageInfo=this.videoApi.queryVideoList(page,pageSize);
                }
        List<Video> records = pageInfo.getRecords();
        if(CollectionUtils.isEmpty(records)){
            return pageResult;
        }
        List<Long>userIds=new ArrayList<>();
        List<VideoVo>videoVoList=new ArrayList<>();
        for (Video record : records) {
            VideoVo videoVo=new VideoVo();
            videoVo.setId(record.getId().toHexString());
            videoVo.setUserId(record.getUserId());
            if(!userIds.contains(record.getUserId())){
                userIds.add(record.getUserId());
            }
            videoVo.setVideoUrl(record.getVideoUrl());
            Long commentCount = this.quanZiApi.queryCommentCount(videoVo.getId(), 2);
            videoVo.setCommentCount(commentCount==null?0:commentCount.intValue());//评论数
            videoVo.setCover(record.getPicUrl());
            videoVo.setHasFocus(1);//TODO 是否关注
            String likeUserKey="QUANZI_COMMENT_LIKE_USER_"+user.getId()+"_"+videoVo.getId();
            videoVo.setHasLiked(this.redisTemplate.hasKey(likeUserKey)?1:0); //是否点赞
            String likeCommentKey="QUANZI_LIKE_COMMENT_"+videoVo.getId();
            String value=this.redisTemplate.opsForValue().get(likeCommentKey);
            if(StringUtils.isNotEmpty(value)){
                videoVo.setLikeCount(Integer.valueOf(value)); //点赞数
            }else{
                videoVo.setLikeCount(0);
            }
            videoVo.setSignature("我就是我~");
            videoVoList.add(videoVo);
        }
        QueryWrapper<UserInfo>queryWrapper=new QueryWrapper<>();
        queryWrapper.in("user_id",userIds);
        List<UserInfo> userInfoList = this.userInfoService.queryUserInfoList(queryWrapper);
        for (VideoVo videoVo : videoVoList) {
            for (UserInfo userInfo : userInfoList) {
                if(videoVo.getUserId().longValue()==userInfo.getUserId().longValue()){
                    videoVo.setAvatar(userInfo.getLogo());
                    videoVo.setNickname(userInfo.getNickName());
                    break;
                }
            }
        }

        pageResult.setItems(videoVoList);
        return pageResult;
    }
    /**
     * @description 关注用户
     * @author
     * @date
     * @param
     *@return
     */
    public Boolean followUser(Long userId) {
        User user=UserThreadLocal.get();
        Boolean bool = this.videoApi.followUser(user.getId(), userId);
        String followUserKey="VIDEO_FOLLOW_USER_"+user.getId()+"_"+userId;
        //记录已关注
        if(!this.redisTemplate.hasKey(followUserKey)){
            this.redisTemplate.opsForValue().set(followUserKey,"1");
        }
        return bool;
    }
    /**
     * @description 取消关注
     * @author
     * @date
     * @param
     *@return
     */
    public Boolean disFollowUser(Long userId) {
        User user=UserThreadLocal.get();
        Boolean bool = this.videoApi.disFollowUser(user.getId(), userId);
        String followUserKey="VIDEO_FOLLOW_USER_"+user.getId()+"_"+userId;
        this.redisTemplate.delete(followUserKey);
        return bool;
    }
}
